extends Control

var peer_connection: WebRTCPeerConnection
var data_channel: WebRTCDataChannel

func _ready():
	# 初始化 WebRTC
	initialize_webrtc()

func initialize_webrtc():
	peer_connection = WebRTCPeerConnection.new()
	peer_connection.ice_candidate_created.connect(_on_ice_candidate)
	peer_connection.session_description_created.connect(_on_session_description)
	
	# 创建数据通道
	data_channel = peer_connection.create_data_channel("chat", {"id": 1, "negotiated": true})
	data_channel.connect("message_received", _on_data_channel_message)

func start_as_offerer():
	peer_connection.create_offer()

func start_as_answerer(offer_sdp):
	peer_connection.set_remote_description("offer", offer_sdp)
	peer_connection.create_answer()

func _on_ice_candidate(mid, index, sdp):
	print("ICE candidate:", sdp)
	# 发送给对等方

func _on_session_description(type, sdp):
	peer_connection.set_local_description(type, sdp)
	print("Session description:", type, sdp)
	# 发送给对等方

func _on_data_channel_message(message):
	print("Received:", message)

func send_message(message: String):
	if data_channel and data_channel.get_ready_state() == WebRTCDataChannel.STATE_OPEN:
		data_channel.send(message)
	else:
		print("Channel not ready")

func set_remote_description(type, sdp):
	peer_connection.set_remote_description(type, sdp)

func add_ice_candidate(mid, index, sdp):
	peer_connection.add_ice_candidate(mid, index, sdp)
